<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AuthController as BaseAuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\ThrottlesLogins;

class AuthController extends BaseAuthController
{
    use ThrottlesLogins;

    public function getLogin()
    {
        if (!Auth::guard('admin')->guest()) {
            return redirect(config('admin.route.prefix'));
        }
        return view('admin.login');
    }

    public function postLogin(Request $request)
    {
        if ($this->hasTooManyLoginAttempts($request)) {
            // 登陆次数过多，锁定账户（需要定义username方法）
            return $this->sendLockoutResponse($request);
        } else {
            $credentials = $request->only(['username', 'password', 'captcha']);
            $validator   = Validator::make($credentials, [
                'username' => 'required',
                'password' => 'required',
                'captcha'  => 'required|captcha'
            ]);
            if ($validator->fails()) {
                return Redirect::back()->withInput()->withErrors($validator);
            }
            unset($credentials['captcha']);
            if (Auth::guard('admin')->attempt($credentials)) {
                admin_toastr(trans('admin.login_successful'));
                return redirect()->intended(config('admin.route.prefix'));
            }

            // 增加错误尝试次数
            $this->incrementLoginAttempts($request);

            return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
        }
    }

    protected function getFailedLoginMessage()
    {
        return Lang::has('auth.failed')
            ? trans('auth.failed')
            : 'These credentials do not match our records.';
    }

    // ThrottlesLogins需要此函数验证
    public function username()
    {
        return 'username';
    }
}
